package com.uniflow.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;

/**
 * 字典数据初始化器
 * 在应用启动时自动插入字典数据到system_configs表
 */
@Component
public class DictDataInitializer implements CommandLineRunner {

    @Autowired
    private JdbcTemplate jdbcTemplate;

    @Override
    public void run(String... args) throws Exception {
        initDictData();
    }

    private void initDictData() {
        try {
            // 检查是否已经存在字典数据
            Integer count = jdbcTemplate.queryForObject(
                "SELECT COUNT(*) FROM system_configs WHERE config_key LIKE 'dict.%'", 
                Integer.class
            );
            
            if (count != null && count > 0) {
                System.out.println("字典数据已存在，跳过初始化");
                return;
            }

            // 插入任务类型字典
            jdbcTemplate.update(
                "INSERT INTO system_configs (id, config_key, config_value, config_type, category, description, is_public, sort_order) VALUES (?, ?, ?, ?, ?, ?, ?, ?)",
                "dict_config_1", 
                "dict.task_types", 
                "[\"manual\", \"workflow\", \"system\", \"approval\", \"review\", \"integration\"]", 
                "json", 
                "dict", 
                "任务类型字典", 
                1, 
                1
            );

            // 插入任务分类字典
            jdbcTemplate.update(
                "INSERT INTO system_configs (id, config_key, config_value, config_type, category, description, is_public, sort_order) VALUES (?, ?, ?, ?, ?, ?, ?, ?)",
                "dict_config_2", 
                "dict.task_categories", 
                "[\"general\", \"development\", \"testing\", \"deployment\", \"approval\", \"data_sync\", \"user_management\", \"system_config\", \"integration\", \"security\"]", 
                "json", 
                "dict", 
                "任务分类字典", 
                1, 
                2
            );

            // 插入任务标签字典
            jdbcTemplate.update(
                "INSERT INTO system_configs (id, config_key, config_value, config_type, category, description, is_public, sort_order) VALUES (?, ?, ?, ?, ?, ?, ?, ?)",
                "dict_config_3", 
                "dict.task_tags", 
                "[\"urgent\", \"important\", \"review\", \"approval\", \"development\", \"testing\", \"deployment\", \"integration\", \"security\", \"maintenance\"]", 
                "json", 
                "dict", 
                "任务标签字典", 
                1, 
                3
            );

            System.out.println("字典数据初始化完成");
        } catch (Exception e) {
            System.err.println("字典数据初始化失败: " + e.getMessage());
            e.printStackTrace();
        }
    }
}